package mi.payment.utils.secure;

import mi.payment.bean.settings.SecurityKeyAreaDistribution;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.utils.iso8583.Utils;

/**
 * 二磁加密工具类
 */
public class TrackEncrypt {

    public static String trackEncrypt(String track) {
        // TODO 磁道暂不加密
        if (true) return track;

        boolean isAdd0 = false;
        if (track.length() % 2 != 0) isAdd0 = true;
        track = track.replaceAll("=", "D");
        byte[] trackBytes = Utils.hexStr2Bytes(track);
        byte[] TDB = new byte[8];
        System.arraycopy(trackBytes, trackBytes.length - 9, TDB, 0, 8);
        int TDKIndex = SecurityKeyAreaDistribution.getTDKIndex(TerminalKeyDataOperations.getInstance().getDes(), 0);
        byte[] out = new byte[8];
        int result = TerminalSecure.dataEncrypt(TDKIndex, 5, (byte) 3, TDB, out);
        if (0 == result) {
            System.arraycopy(out, 0, trackBytes, trackBytes.length - 9, 8);
            track = Utils.byte2HexStr(trackBytes);
        }
        return isAdd0 ? track.substring(0, track.length() - 1) : track;
    }

}

